package com.lishem.top100._06matrix;

import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode.cn/problems/set-matrix-zeroes/description/
 * <p>
 * 给定一个 m x n 的矩阵，如果一个元素为 0 ，则将其所在行和列的所有元素都设为 0 。请使用 原地 算法。
 * <p>
 * 示例 1：
 * <p>
 * 输入：matrix = [[1,1,1],[1,0,1],[1,1,1]]
 * <p>
 * 输出：[[1,0,1],[0,0,0],[1,0,1]]
 * <p>
 * 示例 2：
 * <p>
 * 输入：matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
 * <p>
 * 输出：[[0,0,0,0],[0,4,5,0],[0,3,1,0]]
 */
public class _01LetCode73_矩阵置零 {

    public void setZeroes(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        Set<Integer> rowZero = new HashSet<>();
        Set<Integer> colZero = new HashSet<>();
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 0) {
                    rowZero.add(i);
                    colZero.add(j);
                }
            }
        }
        for (int row : rowZero) {
            for (int i = 0; i < cols; i++) {
                matrix[row][i] = 0;
            }
        }
        for (int col : colZero) {
            for (int i = 0; i < rows; i++) {
                matrix[i][col] = 0;
            }
        }
    }

    public static void main(String[] args) {
        _01LetCode73_矩阵置零 sol = new _01LetCode73_矩阵置零();
        int[][] arr1 = {{1, 1, 1}, {1, 0, 1}, {1, 1, 1}};
        sol.setZeroes(arr1);
        printArray(arr1);
        int[][] arr2 = {{0, 1, 2, 0}, {3, 4, 5, 2}, {1, 3, 1, 5}};
        sol.setZeroes(arr2);
        printArray(arr2);
    }

    public static void printArray(int[][] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
    }
}
